#include<iostream>
#include<signal.h>
#include"../comm/httplib.h"
#include"oj_control.hpp"
using namespace httplib;
using namespace ns_Control;

static Control *ctl_p=nullptr;
void Recovery(int signal)
{
   ctl_p->RecoryMachine();
}

int main()
{

    signal(SIGTSTP,Recovery); //ctrl z发送信号
    //用户请求的服务路由功能(根据用户不同的需求，提供不同的功能)
    Server ser;
    Control ctl;
    ctl_p=&ctl;
    //获取所有的题目列表的网页
    ser.Get("/all_question",[&ctl](const Request& req,Response& resp){
        std::string html;
        ctl.AllQuestion(&html);
        resp.set_content(html,"text/html;charset=utf-8");
    });
    //根据题目编号，获取题目内容
    ser.Get(R"(/question/(\d+))",[&ctl](const Request& req,Response& resp){
     std::string num=req.matches[1];
     std::string html;
     ctl.OneQuestion(num,&html);
     resp.set_content(html,"text/html;charset=utf-8");
    });
    //用户提交的代码。要进行判题功能(1.compile_and_run;2.每道题的测试用例)
    // ser.Post(R"(/judge/(\d+))",[&ctl](const Request req,Response& resp){
    //  std::string num=req.matches[1];
    //  std::string result_json;
    //  ctl.Judge(num,req.body,&result_json);
    //  resp.set_content(result_json,"application/json;charset=utf-8");
    //  //resp.set_content("要被判题的题目: "+num,"text/plain;charset=utf-8");
    // });

        ser.Post(R"(/judge/(\d+))", [&ctl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string result_json;
        ctl.Judge(number, req.body, &result_json);
        resp.set_content(result_json, "application/json;charset=utf-8");
        // resp.set_content("指定题目的判题: " + number, "text/plain; charset=utf-8");
    });


    ser.set_base_dir("./wwwroot");

    ser.listen("0.0.0.0",8080);
    return 0;
}